package com.neu.admin;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.neu.common.RequiresPermissionsDesc;
import com.neu.common.validator.Order;
import com.neu.common.validator.Sort;
import com.neu.doc.AdminAdminController_ResOK;
import com.neu.doc.AdminAdminController_list;
import com.neu.doc.ResponseOK;
import com.neu.domain.ShoppingAdmin;
import com.neu.service.LogHelper;
import com.neu.service.ShoppingAdminService;
import com.neu.util.RegexUtil;
import com.neu.util.ResponseUtil;
import com.neu.util.bcrypt.BCryptPasswordEncoder;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.NotNull;
import java.util.List;

import static com.neu.util.AdminResponseCode.*;

@RestController
@RequestMapping("/admin/admin")
@Validated
public class AdminAdminController {
    private final Log logger = LogFactory.getLog(AdminAdminController.class);

    @Autowired
    private ShoppingAdminService adminService;
    @Autowired
    private LogHelper logHelper;
    
    @ApiOperation(value="获取管理员信息(List)分页数据", notes="分页查询管理员信息",response = AdminAdminController_list.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "integer"),
            @ApiImplicitParam(name = "limit", value = "每页多少条数据", required = true, dataType = "integer"),
            @ApiImplicitParam(name = "sort", value = "排序字段", required = true, dataType = "string"),
            @ApiImplicitParam(name = "order", value = "排序规则", required = true, dataType = "string"),
            @ApiImplicitParam(name = "username", value = "管理员名字", required = false, dataType = "string")
    })
    @RequiresPermissions("admin:admin:list")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String username,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<ShoppingAdmin> adminList = adminService.querySelective(username, page, limit, sort, order);
        return ResponseUtil.okList(adminList);
    }

    private Object validate(ShoppingAdmin admin) {
        String name = admin.getUsername();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }
        if (!RegexUtil.isUsername(name)) {
            return ResponseUtil.fail(ADMIN_INVALID_NAME, "管理员名称不符合规定");
        }
        String password = admin.getPassword();
        if (StringUtils.isEmpty(password) || password.length() < 6) {
            return ResponseUtil.fail(ADMIN_INVALID_PASSWORD, "管理员密码长度不能小于6");
        }
        return null;
    }
    
    @ApiOperation(value="增加管理员", notes="增加一个管理员",response = AdminAdminController_ResOK.class)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "username", value = "管理员名字", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "roleIds", value = "管理员角色", required = true, dataType = "Integer[]"),
//            @ApiImplicitParam(name = "avatar", value = "用户头像", required = false, dataType = "String")
//    })
    @RequiresPermissions("admin:admin:create")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "添加")
    @PostMapping("/create")
    public Object create(@ApiParam(name="ShoppingAdmin對象",value="传入json格式",required=true)
    		@RequestBody ShoppingAdmin admin) {
        Object error = validate(admin);
        if (error != null) {
            return error;
        }

        String username = admin.getUsername();
        List<ShoppingAdmin> adminList = adminService.findAdmin(username);
        if (adminList.size() > 0) {
            return ResponseUtil.fail(ADMIN_NAME_EXIST, "管理员已经存在");
        }

        String rawPassword = admin.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(rawPassword);
        admin.setPassword(encodedPassword);
        adminService.add(admin);
        logHelper.logAuthSucceed("添加管理员", username);
        return ResponseUtil.ok(admin);
    }
    
    @ApiIgnore//使用该注解忽略这个API
    @RequiresPermissions("admin:admin:read")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "详情")
    @GetMapping("/read")
    public Object read(@NotNull Integer id) {
        ShoppingAdmin admin = adminService.findById(id);
        return ResponseUtil.ok(admin);
    }
    

    @ApiOperation(value="编辑管理员", notes="编辑一个管理员",response = AdminAdminController_ResOK.class)
    @RequiresPermissions("admin:admin:update")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@ApiParam(name="ShoppingAdmin對象",value="传入json格式",required=true)
    		@RequestBody ShoppingAdmin admin) {
        Object error = validate(admin);
        if (error != null) {
            return error;
        }

        Integer anotherAdminId = admin.getId();
        if (anotherAdminId == null) {
            return ResponseUtil.badArgument();
        }

        // 不允许管理员通过编辑接口修改密码
        admin.setPassword(null);

        if (adminService.updateById(admin) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        logHelper.logAuthSucceed("编辑管理员", admin.getUsername());
        return ResponseUtil.ok(admin);
    }
    
    @ApiOperation(value="删除管理员", notes="删除一个管理员",response = ResponseOK.class)
//    @ApiImplicitParams({
//    		@ApiImplicitParam(name = "id", value = "管理员id", required = true, dataType = "Integer"),
//            @ApiImplicitParam(name = "username", value = "管理员名字", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "roleIds", value = "管理员角色", required = true, dataType = "Integer[]"),
//            @ApiImplicitParam(name = "avatar", value = "用户头像", required = true, dataType = "String")
//    })
    @RequiresPermissions("admin:admin:delete")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@ApiParam(name="ShoppingAdmin對象",value="传入json格式",required=true)
    		@RequestBody ShoppingAdmin admin) {
        Integer anotherAdminId = admin.getId();
        if (anotherAdminId == null) {
            return ResponseUtil.badArgument();
        }

        // 管理员不能删除自身账号
        Subject currentUser = SecurityUtils.getSubject();
        ShoppingAdmin currentAdmin = (ShoppingAdmin) currentUser.getPrincipal();
        if (currentAdmin.getId().equals(anotherAdminId)) {
            return ResponseUtil.fail(ADMIN_DELETE_NOT_ALLOWED, "管理员不能删除自己账号");
        }

        adminService.deleteById(anotherAdminId);
        logHelper.logAuthSucceed("删除管理员", admin.getUsername());
        return ResponseUtil.ok();
    }
}
